#include "Pinea.h"
#include <SDL3/SDL.h>
#include <SDL3_image/SDL_image.h>
#include <SDL3_mixer/SDL_mixer.h>

// 全局窗口指针
SDL_Window* window;
// 全局渲染器指针
SDL_Renderer* renderer;

// 初始化Pinea引擎，创建窗口、渲染器并初始化音频系统
PINEA_API void pineaInit(const char* title, int width, int height) {
	// 初始化SDL视频和音频子系统
	if (!SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO)) {
		SDL_Log("SDL could not be initialized: %s\n", SDL_GetError());
		return;
	}

	// 创建隐藏且可调整大小的窗口
	window = SDL_CreateWindow(title, width, height, SDL_WINDOW_HIDDEN | SDL_WINDOW_RESIZABLE);
	if (!window) {
		SDL_Log("SDL Window could not be created: %s\n", SDL_GetError());
		return;
	}

	// 创建渲染器
	renderer = SDL_CreateRenderer(window, nullptr);
	if (!renderer) {
		SDL_Log("SDL Renderer could not be created: %s\n", SDL_GetError());
		return;
	}

	// 设置渲染混合模式为混合模式（支持透明度）
	SDL_SetRenderDrawBlendMode(renderer, SDL_BLENDMODE_BLEND);

	// 初始化音频相关
	MIX_InitFlags mixInitFlags = MIX_INIT_MP3 | MIX_INIT_OGG;
	if (Mix_Init(mixInitFlags) != mixInitFlags) {
		SDL_Log("SDL_mixer could not be initialized: %s\n", SDL_GetError());
		return;
	}

	// 配置音频规格
	SDL_AudioSpec audioSpec = {
		.format = SDL_AUDIO_S16, // 16位有符号音频格式
		.channels = 2,			 // 双声道
		.freq = 44100			 // 采样率44100Hz
	};

	// 打开音频设备
	if (!Mix_OpenAudio(0, &audioSpec)) {
		SDL_Log("SDL_mixer could not open audio: %s\n", SDL_GetError());
		return;
	}

	// 分配16个音频通道
	Mix_AllocateChannels(16);
}

// 退出Pinea引擎，释放所有资源
PINEA_API void pineaQuit() {
	SDL_DestroyRenderer(renderer);
	SDL_DestroyWindow(window);
	Mix_CloseAudio();
	SDL_Quit();
}

// 显示窗口
PINEA_API void pineaShow() {
	SDL_ShowWindow(window);
}

// 处理事件队列，将SDL事件转换为Pinea事件
PINEA_API bool pineaPollEvent(PineaEvent* event) {
	SDL_Event e;
	if (SDL_PollEvent(&e)) {
		event->type = e.type;
		// 根据事件类型处理不同的事件数据
		switch (e.type) {
		case SDL_EVENT_KEY_DOWN:
		case SDL_EVENT_KEY_UP:
			event->key = e.key.key; // 存储按键码
			break;
		case SDL_EVENT_MOUSE_BUTTON_DOWN:
		case SDL_EVENT_MOUSE_BUTTON_UP:
			event->key = e.button.button; // 存储鼠标按键码
			break;
		case SDL_EVENT_MOUSE_MOTION:
			event->x = e.motion.x; // 存储鼠标X坐标
			event->y = e.motion.y; // 存储鼠标Y坐标
			break;
		case SDL_EVENT_MOUSE_WHEEL:
			event->x = e.wheel.x; // 存储滚轮X方向移动
			event->y = e.wheel.y; // 存储滚轮Y方向移动
			break;
		case SDL_EVENT_QUIT:
			break;
		}
		return true;
	}
	event->type = SDL_EVENT_FIRST;
	return false;
}

// 清空屏幕为指定颜色
PINEA_API void pineaClear(const PineaColor* color) {
	SDL_SetRenderDrawColor(renderer, color->r, color->g, color->b, color->a);
	SDL_RenderClear(renderer);
}

// 刷新渲染，将绘制内容显示到屏幕
PINEA_API void pineaRender() {
	SDL_RenderPresent(renderer);
}

// 绘制填充矩形
PINEA_API void pineaFillRect(const PineaRect* rect, const PineaColor* color) {
	SDL_SetRenderDrawColor(renderer, color->r, color->g, color->b, color->a);
	SDL_FRect r = { rect->x, rect->y, rect->w, rect->h };
	SDL_RenderFillRect(renderer, &r);
}

// 加载图像文件
PINEA_API PineaImage* pineaLoadImage(const char* path) {
	SDL_Texture* texture = IMG_LoadTexture(renderer, path);
	if (!texture) {
		SDL_Log("Failed to load image: %s", SDL_GetError());
		return nullptr;
	}
	// 设置纹理缩放模式为最近邻（像素风格）
	SDL_SetTextureScaleMode(texture, SDL_SCALEMODE_NEAREST);
	return new PineaImage{ texture, texture->w, texture->h };
}

// 绘制图像
PINEA_API void pineaDrawImage(PineaImage* image,
	const PineaRect* srcRect, const PineaRect* dstRect, double angle, int flip) {
	if (!image) {
		SDL_Log("Failed to draw image: image is null.");
		return;
	}
	SDL_FRect* srcTemp = nullptr;
	if (srcRect) {
		SDL_FRect s = { srcRect->x, srcRect->y, srcRect->w, srcRect->h };
		srcTemp = &s;
	}
	SDL_FRect* dstTemp = nullptr;
	if (dstRect) {
		SDL_FRect d = { dstRect->x, dstRect->y, dstRect->w, dstRect->h };
		dstTemp = &d;
	}
	SDL_RenderTextureRotated(renderer, (SDL_Texture*)image->texture,
		srcTemp, dstTemp, angle, nullptr, (SDL_FlipMode)flip);
}

// 释放图像资源
PINEA_API void pineaDropImage(PineaImage* image) {
	if (!image) {
		SDL_Log("Failed to drop image: image is null.");
		return;
	}
	SDL_DestroyTexture((SDL_Texture*)image->texture);
	delete image;
}

// 加载音乐文件（长时间播放的音频）
PINEA_API PineaAudio* pineaLoadMusic(const char* path) {
	Mix_Music* music = Mix_LoadMUS(path);
	if (!music) {
		SDL_Log("Failed to load music: %s", SDL_GetError());
		return nullptr;
	}
	return new PineaAudio{ music };
}

// 播放音乐
PINEA_API void pineaPlayMusic(PineaAudio* audio, bool loop) {
	if (!audio) {
		SDL_Log("Failed to play music: audio is null.");
		return;
	}
	Mix_Music* music = (Mix_Music*)audio->audio;
	// 循环播放：-1表示无限循环，0表示播放一次
	Mix_PlayMusic(music, loop ? -1 : 0);
}

// 暂停音乐播放
PINEA_API void pineaPauseMusic() {
	Mix_PauseMusic();
}

// 恢复音乐播放
PINEA_API void pineaResumeMusic() {
	Mix_ResumeMusic();
}

// 停止音乐播放
PINEA_API void pineaStopMusic() {
	Mix_HaltMusic();
}

// 释放音乐资源
PINEA_API void pineaDropMusic(PineaAudio* audio) {
	if (!audio) {
		SDL_Log("Failed to drop music: audio is null.");
		return;
	}
	Mix_FreeMusic((Mix_Music*)audio->audio);
	delete audio;
}

// 加载音效文件（短时间播放的音频）
PINEA_API PineaAudio* pineaLoadSound(const char* path) {
	Mix_Chunk* sound = Mix_LoadWAV(path);
	if (!sound) {
		SDL_Log("Failed to load sound: %s", SDL_GetError());
		return nullptr;
	}
	return new PineaAudio{ sound };
}

// 播放音效
PINEA_API void pineaPlaySound(PineaAudio* audio, int loops) {
	if (!audio) {
		SDL_Log("Failed to play sound: audio is null.");
		return;
	}
	// 使用任意可用通道播放音效
	Mix_PlayChannel(-1, (Mix_Chunk*)audio->audio, loops);
}

// 释放音效资源
PINEA_API void pineaDropSound(PineaAudio* audio) {
	if (!audio) {
		SDL_Log("Failed to drop sound: audio is null.");
		return;
	}
	Mix_FreeChunk((Mix_Chunk*)audio->audio);
	delete audio;
}

// 获取当前时间（纳秒级）
PINEA_API uint64_t pineaGetTime() {
	return SDL_GetTicksNS();
}